import { useEffect, useState } from "react";
import ProgDialog, { Dialog, State } from "./ProgDialog";


function render(m: Map<number, Dialog>) {
    const arr = [];
    for (const v of m.values()) {
        arr.push(<ProgDialog key={v.id} show={v.show} title={v.title} msg={v.msg} state={v.state} id={v.id}/>)
    }
    return arr;
}

interface Group {
    m: Map<number, Dialog>
}

function createUnique() {
    const arr = new Uint32Array(1);
    crypto.getRandomValues(arr);
    return arr[0];
}

let createCb = (id: number, dialog: Dialog) => {}
let deleteCb = (id: number) => {}

export async function delay(ms: number) {
    return new Promise((resolve, _) => {
        setTimeout(resolve, ms);
    })
}

export function deleteDialog(id: number) {
    deleteCb(id);
}

export function updateDialog(id: number, dialog: Dialog) {
    createCb(id, dialog);
}

async function test() {
    await delay(100);
    const id = createUnique();
    let d: Dialog = {
        title: 'title',
        state: State.progress,
        msg: 'msg',
        show: true,
        id
    };
    createCb(id, d);
}

test();

function useGroup() {
    const [group, setGroup] = useState<Group>({ m: new Map()  });
    useEffect(()=>{
        createCb = (id, dialog) => {
            group.m.set(id, dialog);
            setGroup( { m: group.m } );
        };
        deleteCb = async (id) => {
            group.m.delete(id);
            setGroup( { m: group.m } );
        }
    }, []);

    return group;
}

const ProgDialogGroup: React.FC = () => {

    const group = useGroup();

    return (
        <>{render(group.m)}</>
    )
}


export default ProgDialogGroup;